package com.example.owner.lettery1.base

import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import com.example.owner.lettery1.R

import com.example.owner.lettery1.modlus.BaseImp
import com.example.owner.lettery1.utils.DialogUtil

abstract class BaseRecyclerViewActivity<P> : AppCompatActivity(), BaseImp<P> {

    var presenter : P ? = null
    var isLoadMore = false //标识可否继续加载
    var pageIndex = 1
    private var toolbar : Toolbar ? = null
    private var swipeRefreshLayout : SwipeRefreshLayout? = null
     var recyclerView : RecyclerView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        presenter = onCreatePresenter()
        onInitView()
        onLoadData()
        setupListener()
    }

    override fun onInitView() {
        setContentView(R.layout.activity_recycler)
        toolbar = findViewById(R.id.toolbar)
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout)
        recyclerView = findViewById(R.id.recyclerView)
        setSupportActionBar(toolbar)
        toolbar!!.setNavigationOnClickListener {
            finish()
        }
        swipeRefreshLayout!!.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark)
        recyclerView!!.layoutManager = LinearLayoutManager(this)
    }

    override fun setupListener() {
        swipeRefreshLayout!!.setOnRefreshListener {
            onRefresh()
        }
    }

     fun onRefresh() {
        onLoadData()
    }

    open fun showOnLoading() {
        DialogUtil.showProgressDialog(supportFragmentManager, this)
        swipeRefreshLayout!!.isRefreshing = true
    }

    open fun hideOnLoading() {
        DialogUtil.hideProgressDialog(supportFragmentManager)
        swipeRefreshLayout!!.isRefreshing = false
    }

    fun addLoadMore() {
        isLoadMore = true
        recyclerView!!.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val lm = recyclerView!!.layoutManager
                val lastVisibleItem = (lm as LinearLayoutManager).findLastVisibleItemPosition()
                val totalItemCount = lm.getItemCount()
                //最后一项
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem == totalItemCount - 1 && isLoadMore) {
                    onLoadMore()
                }
            }
        })
    }

    private fun onLoadMore() {
        pageIndex++
        onLoadData()
    }

    /**
     * 意外终止加载
     */
    open fun onLoadError() {
        if (pageIndex > 1)
            pageIndex--
        //hindLoading()
    }
}